package com.ctw.tinyservices.id.common.lifecycle;

import com.ctw.tinyservices.id.common.enums.state.IdLifecycleState;
import com.ctw.tinyservices.id.common.exception.IdStateException;

/**
 * @author TongWei.Chen  2022/3/7 19:49
 *
 * id生成器生命周期接口
 **/
public abstract class AbstractIdLifecycle implements IdLifecycle {
    private static final String MSG_FORMAT = "前一个状态必须为：%s, 当前为：%s";

    protected IdLifecycleState state = IdLifecycleState.DEFAULT;

    @Override
    public IdLifecycleState getState() {
        return state;
    }

    @Override
    public IdLifecycleState setState(IdLifecycleState state) {
        return this.state = state;
    }

    @Override
    public void init() {
        if (getState() != IdLifecycleState.DEFAULT) {
            throwIdStateException(IdLifecycleState.DEFAULT);
        }
        doInit();
        state = IdLifecycleState.INIT;
    }

    @Override
    public void start() {
        if (getState() != IdLifecycleState.INIT) {
            throwIdStateException(IdLifecycleState.INIT);
        }
        doStart();
        state = IdLifecycleState.START;
    }

    @Override
    public void stop() {
        if (getState() != IdLifecycleState.START) {
            throwIdStateException(IdLifecycleState.START);
        }
        doStop();
        state = IdLifecycleState.STOP;
    }

    /**
     * 避免子类重写麻烦，就不用abstract了
     */
    protected void doInit() {}

    protected void doStart() {}

    protected void doStop() {}

    private void throwIdStateException(IdLifecycleState idLifecycleState) {
        throw new IdStateException(String.format(MSG_FORMAT, idLifecycleState.msg(), getState().msg()));
    }
}
